﻿using Kinlo.Entitys;
using NewLife.Data;
using NewLife.Reflection;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UIWindows.Domains;
using UIWindows.GlobalStatics;
using UIWindows.Services.Context;
using UIWindows.Tools.Helper;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;
using XingLucifer.IBase.Models.PLCInteraktion;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClassAttribute(TaskTypes.后扫码)]
    public class AfterScanCode : ServierBase
    {
        private volatile int _ngScanCode = 0, _ngRearGlueNail = 0;
        public AfterScanCode(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig,
            UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic, MesParameterStatic mesParameterStatic)
            : base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic, mesParameterStatic)
        {
        }

        public override Task Handle(DataContext context)
        {
            if (!ClearSignal(context)) { return Task.CompletedTask; }
            try
            {
                _ngScanCode = 0;
                _ngRearGlueNail = 0;
                var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号).Communication as OmronCIP;
                DateTime weighing_time = DateTime.Now;
                var erinnerungen = ReadOneErinnerungen(plc, context.Address_Struct, context.Struct_Length, _systemConfig.IAddress.Erinnerungen_AfterScanCode, context.AddressingMethod);
                if (erinnerungen.Item1)
                {
                    $"==>>{context.TaskType}<<==\r\n收到启动信号，没收到电池记忆，请联系电气工程师！！！".MessageDialogs(MessageLevelType.错误, false, Enums.PopUpTypes.Global);
                    return base.Handle(context);
                }
                //#region 测高数据获取
                //BatteryBackHeliumDataModel batteryBackHelia = plc.ReadClass<BatteryBackHeliumDataModel>("");//定死的地址
                //RunLog($"-[{context.DeviceIndex}] 接收到的数据：{System.Text.Json.JsonSerializer.Serialize(batteryBackHelia, GlobalStatic.Options)}");
                //#endregion
                RunLog($"记忆ID：{erinnerungen.Item2.SnowflakeId}");
                Models.Devices.DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == context.TaskType
                && x.DeviceType == context.DeviceType && x.Index == context.DeviceIndex);
                if (device == null)
                {
                    RunLog($"找不到[{context.DeviceIndex}]号设备");
                    WriteResult("", ResultTypes.合格, plc, context.Address_Struct, context);
                    return base.Handle(context);
                }
                if (erinnerungen.Item2.SnowflakeId == -1)
                {
                    var barcode_spotCheck = ScanCode(_parameterStatic.RunParameter.Retries_Count_ScanCode, device.Communication, context.DeviceIndex);
                    $"-[{context.DeviceIndex}] 触发点检==>> 扫到的条码：[{barcode_spotCheck}]".RunLog(MessageLevelType.警告);
                    if (!string.IsNullOrEmpty(barcode_spotCheck))
                    {
                        for (int i = 0; i < 3; i++)
                        {
                            if (plc.WriteSingle(barcode_spotCheck, $"{context.Address_Struct}.Code"))
                            {
                                RunLog($"-[{context.DeviceIndex}] 触发点检 条码:[{barcode_spotCheck}] 写入成功!!!");
                                break;
                            }
                            RunLog($"-[{context.DeviceIndex}] 触发点检 条码:[{barcode_spotCheck}] 写入失败 第[{i}]次");
                        }
                    }
                    WriteResult(barcode_spotCheck, (!string.IsNullOrEmpty(barcode_spotCheck) ? ResultTypes.合格 : ResultTypes.不合格), plc, erinnerungen.Item2.Address_Struct, context);
                    return base.Handle(context);
                }
                DateTime dateTime = DateTime.Now;
                ProductionData? entity = _temporaryStatic.EntityCache.FirstOrDefault(x => x.SnowflakeId == erinnerungen.Item2.SnowflakeId);
                if (entity == null)
                {
                    RunLog($"-[{context.DeviceIndex}] 实体缓存查询不到==>[{erinnerungen.Item2.SnowflakeId}]，转到数据库查询");
                    entity = dateTime.GetEntity(context.TaskType, erinnerungen.Item2.SnowflakeId);
                }
                else
                {
                    ProductionData.Meta.TableName = entity.Items["TableName"].ToString();
                }
                if (entity == null)
                {
                    RunLog($"-[{context.DeviceIndex}] 数据库找不到ID为：{erinnerungen.Item2.SnowflakeId}");
                    WriteResult("", ResultTypes.数据库找不到电池, plc, erinnerungen.Item2.Address_Struct, context);
                    return base.Handle(context);
                }
                //if (entity.ResultScanCodeAfterwards == ResultTypes.合格)
                //{
                //    WriteResult(entity.ResultScanCodeAfterwards, plc, erinnerungen.Item2.Address_Struct, context);
                //    return base.Handle(context);
                //}
                //var barcode = ScanCode(_parameterStatic.RunParameter.Retries_Count_ScanCode, device.Communication, context.DeviceIndex);
                //RunLog($"-[{context.DeviceIndex}] ID：[{erinnerungen.Item2.SnowflakeId}] 记忆条码：[{entity.BarCode}] 扫码枪扫出来的码==>>{barcode}");
                //if (_parameterStatic.DecideParameter.EnableEmptyRun)
                //{
                //    RunLog($"-[{context.DeviceIndex}] 检测到启用空跑模式，修改扫码枪扫到的码==>>原始：[{barcode}] 修改后：[{entity.BarCode}]", MessageLevelType.警告);
                //    barcode = entity.BarCode;
                //}
                //try
                //{

                //    //entity.AfterSealPlugHeight = batteryBackHelia.AfterSealingHeight;
                //    //entity.ResultAfterSealPlugHeight = batteryBackHelia.AfterSealingResult != 1 ? ResultTypes.密封塞NG : ResultTypes.合格;
                //    entity.TimeScanCodeAfter = dateTime.GetJSTimeUtc();
                //    entity.ResultScanCodeAfterwards = string.IsNullOrEmpty(barcode) ? ResultTypes.扫码失败 : (barcode == entity.BarCode ? ResultTypes.合格 : ResultTypes.记忆跟踪NG);
                //    if (entity.ResultScanCodeAfterwards != ResultTypes.合格)
                //    {
                //        Interlocked.Increment(ref _ngScanCode);
                //    }
                //    entity.Update();
                //}
                //catch (Exception ex)
                //{
                //    RunLog($"-[{context.DeviceIndex}] 数据库保存异常：{ex}");
                //}
                //WriteResult(entity.ResultScanCodeAfterwards, plc, context.Address_Struct, context);
                _homeStatic.ChartData.NG_AfterScanCode += _ngScanCode;
                _homeStatic.ChartData.NG_RearGlueNail += _ngRearGlueNail;
                _homeStatic.AddOutBattery(entity);
            }
            catch (Exception ex)
            {
                RunLog($"-[{context.DeviceIndex}] 异常：{ex}");
            }
            return base.Handle(context);
        }
    }
}
